<

テキストフィールドへの変更を処理する

場合によっては、テキストが書き込まれるたびにコールバック関数を実行すると便利です。 テキストフィールドが変更されます。たとえば、検索を構築するとよいでしょう。 オートコンプリート機能を備えた画面で、 ユーザーが入力すると結果が表示されます。

テキストが変更されるたびにコールバック関数を実行するにはどうすればよいでしょうか? Flutter には 2 つのオプションがあります。

  1. 供給するonChanged()へのコールバックTextFieldまたはTextFormField
  2. 使うTextEditingController

1.onChanged()へのコールバックTextFieldまたはTextFormField

最も簡単なアプローチは、onChanged()へのコールバックTextFieldまたはTextFormField。 テキストが変更されるたびに、コールバックが呼び出されます。

この例では、テキストフィールドの現在の値を テキストが変更されるたびにコンソールを表示します。

TextField(
  onChanged: (text) {
    print('First text field: $text');
  },
),

2.TextEditingController

より強力ですが、より複雑なアプローチは、TextEditingControllerとしてcontrollerの財産TextFieldまたはTextFormField

テキストが変更されたときに通知を受け取るには、コントローラーの音を聞いてください を使用してaddListener()次の手順を使用する方法:

  1. を作成しますTextEditingController
  2. を接続します。TextEditingControllerテキストフィールドに。
  3. 最新の値を出力する関数を作成します。
  4. コントローラーの変化を聞きます。

を作成しますTextEditingController

を作成しますTextEditingController:

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Create a text controller. Later, use it to retrieve the
  // current value of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the
    // widget tree.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Fill this out in the next step.
  }
}

を接続します。TextEditingControllerテキストフィールドに

供給してくださいTextEditingControllerどちらかにTextFieldまたはTextFormField。これら 2 つのクラスを接続すると、 テキストフィールドへの変更の監視を開始できます。

TextField(
  controller: myController,
),

最新の値を出力する関数を作成する

テキストが変更されるたびに実行する関数が必要です。 でメソッドを作成します。_MyCustomFormState印刷するクラス テキストフィールドの現在の値を出力します。

void _printLatestValue() {
  print('Second text field: ${myController.text}');
}

コントローラーの変更を聞く

最後に聴いてみてくださいTextEditingControllerそして、_printLatestValue()テキストが変更されたときのメソッド。使用addListener()この目的のためのメソッド。

次の時点で変更の監視を開始します。_MyCustomFormStateクラスが初期化され、 そして、次の時点で聞くのをやめます_MyCustomFormState処分される。

@override
void initState() {
  super.initState();

  // Start listening to changes.
  myController.addListener(_printLatestValue);
}
@override
void dispose() {
  // Clean up the controller when the widget is removed from the widget tree.
  // This also removes the _printLatestValue listener.
  myController.dispose();
  super.dispose();
}

インタラクティブな例

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Retrieve Text Input',
      home: MyCustomForm(),
    );
  }
}

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void initState() {
    super.initState();

    // Start listening to changes.
    myController.addListener(_printLatestValue);
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the widget tree.
    // This also removes the _printLatestValue listener.
    myController.dispose();
    super.dispose();
  }

  void _printLatestValue() {
    print('Second text field: ${myController.text}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Retrieve Text Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              onChanged: (text) {
                print('First text field: $text');
              },
            ),
            TextField(
              controller: myController,
            ),
          ],
        ),
      ),
    );
  }
}
お父さん0c3f0-f0b5-4688-84ed-1cd87fdc0bff